package com.pzsh.controller;

import com.alibaba.fastjson.JSONObject;
import com.pzsh.entity.ResponseWrapper;
import com.pzsh.entity.SpecialEntity;
import com.pzsh.entity.TransactionEntity;
import com.pzsh.entity.UserEntity;
import com.pzsh.entity.vo.SpecialVo;
import com.pzsh.entity.vo.TransactionVo;
import com.pzsh.entity.vo.UserPackVo;
import com.pzsh.enums.ErrorCodeEnum;
import com.pzsh.exception.ApiException;
import com.pzsh.jwt.CurrentManager;
import com.pzsh.service.IIntegralService;
import com.pzsh.service.IUserService;
import com.pzsh.swagger.ApiJsonObject;
import com.pzsh.swagger.ApiJsonProperty;
import com.pzsh.util.Asserts;
import com.pzsh.util.PageResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * @program: 接口【积分】
 * @description:
 * @author: gxl
 * @create:
 **/
@Slf4j
@Api(value = "integral", tags = "积分")
@RestController
@RequestMapping("/integral")
public class IntegralController {

    @Autowired
    private IIntegralService integralService;

    @Autowired
    private IUserService iUserService;

    @CurrentManager
    @RequestMapping(value = "/showIntegral", method = RequestMethod.POST)
    @ApiOperation(tags = "积分", httpMethod = "POST", value = "[前端]查询用户积分", response = UserPackVo.class)
    public ResponseWrapper showIntegral(
            @ApiJsonObject(name = "showIntegralParams", value = {}) @RequestBody JSONObject jsonParam) {

        try {
            String account = jsonParam.getString("account");
            Asserts.checkAccount(account,"用户名");
            UserPackVo vo = integralService.selectIntegralByAccount(account);
            return ResponseWrapper.succeed(vo);
        }catch (ApiException e){
            log.error(String.format("[前端]查询用户积分失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[前端]查询用户积分失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @RequestMapping(value = "/notify", method = RequestMethod.POST)
    @ApiOperation(tags = "积分", httpMethod = "POST", value = "[前端]rd 回调", response = UserPackVo.class)
    public ResponseWrapper notify(
            @ApiJsonObject(name = "notifyParams", value = {}) @RequestParam HashMap<String,Object> map) {
        try {
            log.info("开始接收 RD 通知");
            //{api:"changeLevel", username:"test", level:1}
//            String content = String.valueOf(map.get("content"));
//            JSONObject jsonObject = JSONObject.parseObject(content);
//            String api = jsonObject.getString("api");
//            String account = jsonObject.getString("username");
//            Integer level = jsonObject.getInteger("level");

            String content = String.valueOf(map.get("data"));
            JSONObject jsonObject = JSONObject.parseObject(content);
            String api = jsonObject.getString("api");
            String account = jsonObject.getString("username");
            Integer level = jsonObject.getInteger("level");

//            String api = String.valueOf(map.get("api"));
//            String account = String.valueOf(map.get("username"));
//            Integer level = (Integer) map.get("level");

            log.info("接收 RD 通知：api:{},username:{},level:{}",api,account,level);
            if (api.equals("changeLevel")){//等级变更回调
                UserEntity entity = new UserEntity();
                entity.setAccount(account);
                iUserService.toGrade(account,level);
            }
            if (api.equals("changeWallet")){//钱包变更回调
                // {api:"changeWallet", username:"test", wallet: 1, value:100}
//                String wallet = String.valueOf(map.get("wallet"));
//                String RD = String.valueOf(map.get("value"));
//                integralService.updateUserPack(account);
            }
            return ResponseWrapper.succeed();
        }catch (ApiException e){
            log.error(String.format("[前端]回调失败，参数:%s, 错误信息:%s", "jsonParam.toJSONString()", e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[前端]回调失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentManager
    @RequestMapping(value = "/psTransfer", method = RequestMethod.POST)
    @ApiOperation(tags = "积分", httpMethod = "POST", value = "[前端]ps转账/赠送ps转账", response = String.class)
    public ResponseWrapper psTransfer(
            @ApiJsonObject(name = "psTransferParams", value = {
                    @ApiJsonProperty(key = "numb", value = "数量"),
                    @ApiJsonProperty(key = "mobile", value = "对方手机号"),
                    @ApiJsonProperty(key = "vcode", value = "手机短信验证码"),
                    @ApiJsonProperty(key = "payPwd", value = "支付密码"),
                    @ApiJsonProperty(key = "tranType", value = "类型：0：自由积分，1：赠送积分")
            }) @RequestBody JSONObject jsonParam) {
        try {

            Double numb = (Double.valueOf(jsonParam.getString("numb")) * 100);
            Integer iii = numb.intValue();
            Asserts.naturalNumber(iii, "PS数量");

//            Integer iii = jsonParam.getInteger("numb");
            String mobile = jsonParam.getString("mobile");
            String vcode = jsonParam.getString("vcode");
            String payPwd = jsonParam.getString("payPwd");
            String account = jsonParam.getString("account");
            Integer tranType = jsonParam.getInteger("tranType");
            Asserts.naturalNumb(tranType, "账户类型");
            Asserts.checkVcode(vcode, "验证码");
            Asserts.checkMobile(mobile, "手机号码");
            Asserts.checkAccount(account, "用户名");
            Asserts.checkPsw(payPwd, "支付密码");
            Asserts.naturalNumber(iii, "PS数量");

            if (tranType.equals(0)){
                integralService.psTransfer(account, mobile, iii, payPwd, vcode);
            }else{
                integralService.rewardPsTransfer(account, mobile, iii, payPwd, vcode);
            }

            return ResponseWrapper.succeed();
        }catch (ApiException e){
            log.error(String.format("[前端]ps转账/赠送ps转账失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[前端]ps转账/赠送ps转账失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }



    @CurrentManager
    @RequestMapping(value = "/RD2PS", method = RequestMethod.POST)
    @ApiOperation(tags = "积分", httpMethod = "POST", value = "[前端]RD转PS", response = String.class)
    public ResponseWrapper RD2PS(
            @ApiJsonObject(name = "RD2PSParams", value = {}) @RequestBody JSONObject jsonParam) {
        try {
            String account = jsonParam.getString("account");
            Asserts.checkAccount(account, "用户名");

            integralService.RD2PS(account);
            return ResponseWrapper.succeed();
        }catch (ApiException e){
            log.error(String.format("[前端]RD转PS失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[前端]RD转PS失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentManager
    @RequestMapping(value = "/getVerificationCodeOfPS", method = RequestMethod.POST)
    @ApiOperation(tags = "积分", httpMethod = "POST", value = "[前端]用户获取 “ps转账” 验证码", response = String.class)
    public ResponseWrapper getVerificationCodeOfPS(
            @ApiJsonObject(name = "getVerificationCodeOfPSParams", value = {
                    @ApiJsonProperty(key = "mobile", value = "手机号")
            }) @RequestBody JSONObject jsonParam) {
        try {
            String mobile = jsonParam.getString("mobile");
            Asserts.checkMobile(mobile,"手机号码");
            String account = jsonParam.getString("account");
            Asserts.checkAccount(account, "用户名");

            integralService.sendVerificationCodeForPS(account);
            return ResponseWrapper.succeed("发送成功");
        }catch (ApiException e){
            log.error(String.format("[前端]用户获取 “ps转账” 验证码失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[前端]用户获取 “ps转账” 验证码失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentManager
    @RequestMapping(value = "/getTrans", method = RequestMethod.POST)
    @ApiOperation(tags = "积分", httpMethod = "POST", value = "[前端]用户获取明细列表", response = List.class)
    public ResponseWrapper getTrans(
            @ApiJsonObject(name = "getTransParams", value = {
                    @ApiJsonProperty(key = "pageSize", value = "页码"),
                    @ApiJsonProperty(key = "rowSize", value = "行数"),
                    @ApiJsonProperty(key = "recordType", value = "类型：0: 全部，1：转换记录，2：提现记录，3：充值记录")
            }) @RequestBody JSONObject jsonParam) {
        try {

            String account = jsonParam.getString("account");
            Asserts.notBlank(account, "用户名");

            Integer recordType = jsonParam.getInteger("recordType");
            Asserts.naturalNumber(recordType, "订单状态");

            Integer pageSize = jsonParam.getInteger("pageSize");
            Integer rowSize = jsonParam.getInteger("rowSize");
            if (pageSize==null|| "".equals(pageSize)){
                pageSize = 0;
            }
            if (rowSize == null || "".equals((rowSize))){
                rowSize = 10;
            }

            PageResult<List<TransactionVo>> list = integralService.getTrans(account, recordType, pageSize, rowSize);
            return ResponseWrapper.succeed(list.getTotal(), list.getData());

        }catch (ApiException e){
            log.error(String.format("[前端]用户获取明细列表失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[前端]用户获取明细列表失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentManager
    @RequestMapping(value = "/getPzshMiner", method = RequestMethod.POST)
    @ApiOperation(tags = "积分", httpMethod = "POST", value = "获取矿工费和Pzsh市价", response = List.class)
    public ResponseWrapper getPzshMiner(
            @ApiJsonObject(name = "getPzshMinerParams", value = {}) @RequestBody JSONObject jsonParam) {
        try {
            List<SpecialVo> SpecialEntitys = integralService.getPzshMiner();
            return ResponseWrapper.succeed(SpecialEntitys);
        } catch (ApiException e) {
            log.error(String.format("[后台]获取矿工费失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error(String.format("[后台]获取矿工费失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }
    @CurrentManager
    @RequestMapping(value = "/LevelRule", method = RequestMethod.POST)
    @ApiOperation(tags = "积分", httpMethod = "POST", value = "[前端]获取升级规则", response = String.class)
    public ResponseWrapper LevelRule(
            @ApiJsonObject(name = "LevelRuleParams", value = {}) @RequestBody JSONObject jsonParam) {
        try {
            String levelRule = iUserService.getLevelRule();
            return ResponseWrapper.succeed(levelRule);
        } catch (ApiException e) {
            log.error(String.format("[前端]获取升级规则失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error(String.format("[前端]获取升级规则失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentManager
    @RequestMapping(value = "/getRdRecord", method = RequestMethod.POST)
    @ApiOperation(tags = "积分", httpMethod = "POST", value = "[前端]RD收益记录", response = String.class)
    public ResponseWrapper getRdRecord(
            @ApiJsonObject(name = "getRdRecordParams", value = {
                    @ApiJsonProperty(key = "pageSize", value = "页码"),
            }) @RequestBody JSONObject jsonParam) {
        try {
            String account = jsonParam.getString("account");
            Asserts.notBlank(account, "用户名");

            Integer pageSize = jsonParam.getInteger("pageSize");
            if (pageSize == null || "".equals(pageSize)){
                pageSize = 0;
            }

            JSONObject json = iUserService.getRdRecord(account, String.valueOf(pageSize));
            return ResponseWrapper.succeed(json);
        } catch (ApiException e) {
            log.error(String.format("[前端]RD收益记录失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error(String.format("[前端]RD收益记录失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

}
